package com.liang.blog.security.aspect;

import com.liang.blog.common.exception.BlogException;
import com.liang.blog.common.result.ResultCodeEnum;
import com.liang.blog.model.constant.SecurityConstants;
import com.liang.blog.security.annotation.HasPermission;
import com.liang.blog.security.utils.BlogSecurityUtil;
import com.liang.blog.vo.user.LoginUserVo;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author：YanWenLiang
 * @Date:2023-08-25-16:35
 */
@Aspect
@Component
public class AuthorizeAspect {

    @Pointcut("@annotation(com.liang.blog.security.annotation.HasPermission)")
    public void pointcut(){

    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{

        // 注解鉴权
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        this.checkMethodAnnotation(signature.getMethod());
        try
        {
            // 执行原有逻辑
            Object obj = proceedingJoinPoint.proceed();
            return obj;
        }
        catch (Throwable e)
        {
            throw e;
        }
    }

    /**
     * 权限的判断
     * @param method
     */
    public void checkMethodAnnotation(Method method){
        HasPermission annotation = method.getAnnotation(HasPermission.class);
        String perm = annotation.value();

        LoginUserVo loginUserVo = BlogSecurityUtil.get(SecurityConstants.LOGIN_USER, LoginUserVo.class);
        Set<String> permissions = loginUserVo.getPermissions();

        // 判断权限
        if (permissions.contains("*:*:*")) return;

        // 用户不包含该权限则抛出异常
        if (!permissions.contains(perm)){
            throw new BlogException(ResultCodeEnum.PERMISSION);
        }
    }
}
